<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 优惠券
 *
 */
class Coupon extends Backend
{
    /**
     * Coupon模型对象
     * @var \app\admin\model\Coupon
     */
    protected $model = null;

    protected $quickSearchField = ['coupon.id', 'coupon.coupon_name'];

    protected $defaultSortField = 'id,desc';

    protected $withJoinTable = ['goods', 'category'];

    protected $preExcludeFields = ['createtime', 'updatetime'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Coupon;
    }

    public function select()
    {
        $time = time();
        $this->model = $this->model->whereRaw("(coupon_type = 0 && start_time < {$time} && end_time > {$time}) or coupon_type=1");
    }

    public function edit()
    {
        $id = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            if (!isset($data['start_time']) || !isset($data['end_time'])) $this->error('请选择有效时间段');
            if ($data['coupon_type'] == 1 && $data['days'] <= 0) $this->error('请输入有效天数');
            if ($data['coupon_type'] == 0 && strtotime($data['end_time']) <= strtotime($data['start_time'])) $this->error('请选择有效时间段');
            if ($data['num'] <= 0) $this->error('请输入有效数量');

            $data = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row,
        ]);
    }

}